/*
 * Copyright 1999-2006 Alibaba.com
 * 
 * Licensed under Alibaba company: http://www.alibaba.com
 */

package com.biqee.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;


public class HttpUtil {


	/**
	 * 
	 * 根据url 获得http response返回结果字符串。
	 * @author Michael Weng
	 * @param url
	 * @return
	 * @throws IOException
	 */
	public static String getHttpResponse(String url, String encoding) throws IOException{
		if(encoding==null || "".equals(encoding)){
			encoding = Charset.defaultCharset().name();
		}
		
		String result = null ;
		if(url.indexOf("//")==-1){
			url = "http://"+url ;
		}
		HttpClient httpClient = new HttpClient();
	
		GetMethod getMethod = new GetMethod(url);
		
		InputStream inputStream = null;	
		ByteArrayOutputStream bos = null;
		try{		
			getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,new DefaultHttpMethodRetryHandler()); 
			//执行
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) 
			{   
	
			    throw new IOException("connect url error:" + getMethod.getStatusLine()+" url: "+url);
			}else{
				
				inputStream = getMethod.getResponseBodyAsStream();
				bos = new ByteArrayOutputStream();
		        IOUtils.copy(inputStream, bos);
		        result = new String(bos.toByteArray(),encoding);      
			
			}
		}catch(IOException e){			
			throw e ;
		}finally{				
			getMethod.releaseConnection();
			if(inputStream!=null) inputStream.close();
			if(bos!=null) bos.close();
		}	
		
		return result.toString();
	}
	
	public static void main(String[] args) throws IOException {
    String url ="http://rss.cnforex.com/rss/paijia.xml";
   
	String a =	HttpUtil.getHttpResponse(url, "GBK");
	System.out.println(a);
		
	}


	
	
}
